package com.yusong.open.sdk.utils;

import com.google.gson.Gson;
import okhttp3.*;

import java.util.concurrent.TimeUnit;

/**
 * Created by yusong on 2018/7/9.
 * 基于OKHttp的网络请求工具类
 */
public class OkHttpUtil {

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    //初始化
    private static final OkHttpClient client = new OkHttpClient.Builder()
            .retryOnConnectionFailure(true)
            .connectTimeout(15, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .addInterceptor(new HttpLogInterceptor())
            .build();

    /**
    *发送POST Json请求
    */
    public static String postJson(String url, String json) throws Exception {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    /**
     * 发送POST Json请求
     * @param url
     */
    public static String postJson(String url, Object req) throws Exception {
        Gson gson = new Gson();
        String reqJson = gson.toJson(req);
        return postJson(url,reqJson);
    }


    
    public static String get(String url) throws Exception {
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }
    
    public static void main(String[] args) throws Exception {
    	String url = "http://localhost:8000/index";
    	String result = OkHttpUtil.get(url);
    	System.out.println(result);
	}
}
